#include "dialoguser.h"
#include "ui_dialoguser.h"
#include <QStyledItemDelegate>
#include "Account.h"

DialogUser::DialogUser(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogUser)
{
    ui->setupUi(this);

	ui->labelError->hide();

    QStyledItemDelegate* itemDelegate = new QStyledItemDelegate();
    ui->comboBoxName->setItemDelegate(itemDelegate);
    ui->comboBoxName->setStyleSheet("QComboBox QAbstractItemView::item {min-height: 28px;}");
}

DialogUser::~DialogUser()
{
    delete ui;
}

void DialogUser::setUser(const QString& user)
{
    m_user = user;

    bool isSuperAdmin = Account::isSuperAdmin(m_user);
    ui->pushButtonReset->setVisible(isSuperAdmin);
}

void DialogUser::on_pushButtonOK_clicked()
{
	QString name = ui->comboBoxName->currentText();
	QString password = ui->lineEditOld->text();

	QString newPassword = ui->lineEditNew->text();
	QString confirmPassword = ui->lineEditConfirm->text();
	if (newPassword != confirmPassword)
	{
		ui->labelError->setText("new password is not identical.");
		ui->labelError->show();
		return;
	}

	if (newPassword.isEmpty())
	{
		ui->labelError->setText("new password can not by empty.");
		ui->labelError->show();
		return;
	}

	if (checkAccount(name, password))
	{
		m_dataStore->setValue(name.toStdString(), newPassword.toStdString());

		accept();
	}
	else
	{
		ui->labelError->setText("password is not correct");
		ui->labelError->show();
	}
}

void DialogUser::on_pushButtonCancel_clicked()
{
    reject();
}

void DialogUser::setDataStore(std::shared_ptr< SecureDataStore>& dataStore)
{
    m_dataStore = dataStore;

    std::vector< std::string >	users;
    m_dataStore->getKeys(users);

    if (Account::isSuperAdmin(m_user))
    {
        for (size_t i = 0; i < users.size(); ++i)
        {
            std::string& user = users[i];
            ui->comboBoxName->addItem(user.c_str());
        }
    }
    else
    {
        ui->comboBoxName->addItem(m_user);
    }
}

bool DialogUser::checkAccount(const QString& name, const QString& password)
{
    std::string value;
    m_dataStore->getValue(name.toStdString(), value);
    return value == password.toStdString();
}

void DialogUser::on_pushButtonReset_clicked()
{
    m_dataStore->setValue(Account::ADMIN, Account::ADMIN);
}
